import { _decorator, Color, Component, Label, Node, randomRange, renderer, Sprite } from 'cc';
import { GameData } from '../system/GameData';
import { database } from 'wx-server-sdk';
import { DataHelper } from '../system/DataHelper';
import { Loader } from '../tools/LoadManger';
import { Tools } from '../tools/Tools';
import { AppControll, ConfigKey, PopView } from '../manager/AppControll';
import { PopManager } from '../manager/PopManager';
import { SystemMessage } from './SystemMessage';
import { SoundManager } from '../manager/SoundManger';
const { ccclass, property } = _decorator;

export type randomGunWeight = {
    key: number,
    weight: number,
}

enum RandomState {
    normal = "upgradeUse",
    upgrading = "upgrading",
    max = "max"
}

@ccclass('SecondGunRandom')
export class SecondGunRandom extends Component {
    private mNdBlueStuff: Node = null;
    private mNdPurpleStuff: Node = null;
    private mNdYellowStuff: Node = null;
    private mNdRedStuff: Node = null;
    private mNdCurLevel: Node = null;
    private mNdNextLevel: Node = null;
    private mNdUpgradeUse: Node = null;
    private mNdupgrading: Node = null;
    private mNdaxLevel: Node = null;
    private mNdVideoCutTime: Node = null;
    private mState: RandomState = RandomState.normal;
    private mRes = {
        1: "reward_month_icon_gold",
        3: "blueStuff",
        4: "purpleStuff",
        5: "yellowStuff",
        6: "redStuff",
    }
    private playDataKey = {
        1: "Gold",
        3: "blueStuff",
        4: "purpleStuff",
        5: "yellowStuff",
        6: "redStuff",
    }
    isLock: any;

    protected onLoad(): void {
        let body = this.node.getChildByName("body");
        let ndUpgrade = body.getChildByName("upgrade");
        this.mNdBlueStuff = this.node.getChildByName("blueStuff");
        this.mNdPurpleStuff = this.node.getChildByName("purpleStuff");
        this.mNdYellowStuff = this.node.getChildByName("yellowStuff");
        this.mNdRedStuff = this.node.getChildByName("redStuff");
        this.mNdCurLevel = body.getChildByName("nowLevel");
        this.mNdNextLevel = body.getChildByName("nextLevel");
        this.mNdUpgradeUse = ndUpgrade.getChildByName("upgradeUse");
        this.mNdupgrading = ndUpgrade.getChildByName("upgrading");
        this.mNdaxLevel = ndUpgrade.getChildByName("maxLevel");
        this.mNdVideoCutTime = this.mNdupgrading.getChildByName("cutTimes").getChildByName("LbCount");
        this.InitUpgrade();
    }

    InitStuffCount() {
        this.mNdBlueStuff.getChildByName("Label").getComponent(Label).string = GameData.playerData.blueStuff + "";
        this.mNdPurpleStuff.getChildByName("Label").getComponent(Label).string = GameData.playerData.purpleStuff + "";
        this.mNdYellowStuff.getChildByName("Label").getComponent(Label).string = GameData.playerData.yellowStuff + "";
        this.mNdRedStuff.getChildByName("Label").getComponent(Label).string = GameData.playerData.redStuff + "";
    }

    InitCurLevel() {
        let level = GameData.playerData.randomLevel;
        if (level == undefined) {
            GameData.playerData.randomLevel = 0;
            level = 0;
        }
        this.mNdCurLevel.getChildByName("nowLevel").getComponent(Label).string = level + ""
        let lt: randomGunWeight[] = [];
        DataHelper.GetRandomLvelConfigByLv(level, lt);
        if (lt.length != 0) {
            let tempLt: Node[] = [];
            let probability = this.mNdCurLevel.getChildByName("probability");
            tempLt.push(probability.getChildByName("gray"));
            tempLt.push(probability.getChildByName("green"));
            tempLt.push(probability.getChildByName("blue"));
            tempLt.push(probability.getChildByName("purple"));
            tempLt.push(probability.getChildByName("yellow"));
            tempLt.push(probability.getChildByName("red"));
            let count = 0;
            this.GetWeightByLt(lt).forEach(str => {
                tempLt[count].getChildByName("odds").getComponent(Label).string = str
                count++;
            });
        }
    }

    InitNextLevel() {
        let level = GameData.playerData.randomLevel;
        if (level == undefined) {
            GameData.playerData.randomLevel = 1;
            level = 1;
        } else {
            level = GameData.playerData.randomLevel + 1;
        }
        this.mNdNextLevel.getChildByName("nextLevel").getComponent(Label).string = level + ""
        let lt: randomGunWeight[] = [];
        DataHelper.GetRandomLvelConfigByLv(level, lt);
        if (lt.length != 0) {
            this.mNdNextLevel.getChildByName("Label").active = true;
            let tempLt: Node[] = [];
            let probability = this.mNdNextLevel.getChildByName("probability");
            tempLt.push(probability.getChildByName("gray"));
            tempLt.push(probability.getChildByName("green"));
            tempLt.push(probability.getChildByName("blue"));
            tempLt.push(probability.getChildByName("purple"));
            tempLt.push(probability.getChildByName("yellow"));
            tempLt.push(probability.getChildByName("red"));
            let count = 0;
            this.GetWeightByLt(lt).forEach(str => {
                tempLt[count].getChildByName("odds").getComponent(Label).string = str;
                count++;
            });
        } else {
            let tempLt: Node[] = [];
            let probability = this.mNdNextLevel.getChildByName("probability");
            tempLt.push(probability.getChildByName("gray"));
            tempLt.push(probability.getChildByName("green"));
            tempLt.push(probability.getChildByName("blue"));
            tempLt.push(probability.getChildByName("purple"));
            tempLt.push(probability.getChildByName("yellow"));
            tempLt.push(probability.getChildByName("red"));
            tempLt.forEach(nd => {
                nd.getChildByName("odds").getComponent(Label).string = "";
            })
            this.mNdNextLevel.getChildByName("nextLevel").getComponent(Label).string = "";
            this.mNdNextLevel.getChildByName("Label").active = false;
        }
    }

    InitUpgrade() {
        this.InitStuffCount();
        this.InitCurLevel();
        this.InitNextLevel();
        let level = GameData.playerData.randomLevel;
        if (level == undefined) {
            GameData.playerData.randomLevel = 1;
            level = 1;
        } else {
            level = GameData.playerData.randomLevel + 1;
        }

        let lt = [];
        DataHelper.GetRandomLvelConfigByLv(level, lt)
        if (lt.length == 0) {
            this.mState = RandomState.max;
            this.mNdUpgradeUse.active = false;
            this.mNdupgrading.active = false;
            this.mNdaxLevel.active = true;
            return;
        }
        if (GameData.playerData.upgradeTime == null && GameData.playerData.upgradeTime == undefined) {
            this.mState = RandomState.normal;
            this.mNdUpgradeUse.active = true;
            this.mNdupgrading.active = false;
            this.InitSpend();
        } else {
            this.mState = RandomState.upgrading;
            this.mNdUpgradeUse.active = false;
            this.mNdupgrading.active = true;
            this.InitUpdating();
        }
        this.mNdVideoCutTime.getComponent(Label).string = "倒计时-" + DataHelper.GetConfigByKey(ConfigKey.videoCutTime).value + "s";
    }

    InitSpend() {
        let ndNeed = this.mNdUpgradeUse.getChildByName("upgradeNeed");
        let level = GameData.playerData.randomLevel;
        if (level == undefined) {
            GameData.playerData.randomLevel = 1;
            level = 1;
        } else {
            level = GameData.playerData.randomLevel + 1;
        }
        let config = DataHelper.GunRandomSpendConfigByLv(level);
        let count = 0;
        ndNeed.children.forEach(nd => {
            if (config.upgradeSpend[count]) {
                nd.active = true;
                Loader.GetTurnTableRewardImage("rewardIcon/" + this.mRes[config.upgradeSpend[count][0]], (spf) => {
                    if (!nd.getChildByName("item_icon")) return;
                    nd.getChildByName("item_icon").getComponent(Sprite).spriteFrame = spf;
                })
                nd.getChildByName("itemNum").getComponent(Label).string = config.upgradeSpend[count][1] + "";
                if (config.upgradeSpend[count][1] <= GameData.playerData[this.playDataKey[config.upgradeSpend[count][0]]]) {
                    nd.getChildByName("itemNum").getComponent(Label).color = new Color(DataHelper.GetConfigByKey(ConfigKey.propEnough).value);
                } else {
                    nd.getChildByName("itemNum").getComponent(Label).color = new Color(DataHelper.GetConfigByKey(ConfigKey.propFail).value);
                }
            }
            count++;
        })
        let ndUseTime = this.mNdUpgradeUse.getChildByName("upgradeUseTime");
        ndUseTime.getChildByName("Label-001").getComponent(Label).string = Tools.formatCountdown(config.upgradeCountDown);
        let isEnough = true;
        config.upgradeSpend.forEach(element => {
            let num = element[1]
            if (GameData.GetNumByType(element[0]) < num) {
                isEnough = false;
            };
        });
        this.mNdUpgradeUse.getChildByName("upgradeBtn").getChildByName("yellowPoint").active = isEnough;
    }

    InitUpdating() {
        let level = GameData.playerData.randomLevel;
        if (level == undefined) {
            GameData.playerData.randomLevel = 1;
            level = 1;
        } else {
            level = GameData.playerData.randomLevel + 1;
        }
        let ctLabel = this.mNdupgrading.getChildByName("Label").getComponent(Label);
        if (!GameData.playerData.upgradeTime) {
            this.mState == RandomState.normal;
            this.InitUpgrade();
            return
        }
        let now = Date.now();
        let countDown = GameData.playerData.upgradeTotal * 1000 - (now - GameData.playerData.upgradeTime);
        if (countDown >= 0) {
            ctLabel.string = Tools.formatCountdown(countDown / 1000) + "后完成";
        } else {
            this.mState == RandomState.normal
        }
    }

    GetWeightByLt(lt: randomGunWeight[]): string[] {
        let totalQuality0 = 0;
        let totalQuality1 = 0;
        let totalQuality2 = 0;
        let totalQuality3 = 0;
        let totalQuality4 = 0;
        let totalQuality5 = 0;
        lt.forEach(elemt => {
            let config = DataHelper.GetSpecialSkillConfigById(elemt.key);
            switch (config.skillQuality) {
                case 0:
                    totalQuality0 += elemt.weight;
                    break;
                case 1:
                    totalQuality1 += elemt.weight;
                    break;
                case 2:
                    totalQuality2 += elemt.weight;
                    break;
                case 3:
                    totalQuality3 += elemt.weight;
                    break;
                case 4:
                    totalQuality4 += elemt.weight;
                    break;
                case 5:
                    totalQuality5 += elemt.weight;
                    break;
            }
        })
        let result = [];
        let total = totalQuality0 + totalQuality1 + totalQuality2 + totalQuality3 + totalQuality4 + totalQuality5;
        result.push((totalQuality0 / total * 100).toFixed(2) + "%");
        result.push((totalQuality1 / total * 100).toFixed(2) + "%");
        result.push((totalQuality2 / total * 100).toFixed(2) + "%");
        result.push((totalQuality3 / total * 100).toFixed(2) + "%");
        result.push((totalQuality4 / total * 100).toFixed(2) + "%");
        result.push((totalQuality5 / total * 100).toFixed(2) + "%");
        return result;
    }

    protected update(dt: number): void {
        if (this.mState == RandomState.normal) return;
        this.InitUpdating();
    }

    OnBtnUpdate() {
        let level = GameData.playerData.randomLevel;
        SoundManager.Instance<SoundManager>().PlayEffect(GameData.btnClick);
        if (level == undefined) {
            GameData.playerData.randomLevel = 1;
            level = 1;
        } else {
            level = GameData.playerData.randomLevel + 1;
        }
        let config = DataHelper.GunRandomSpendConfigByLv(level);
        let isEnough = true;
        config.upgradeSpend.forEach(element => {
            let num = element[1]
            if (GameData.GetNumByType(element[0]) < num) {
                isEnough = false;
            };
        });
        if (!isEnough) {
            PopManager.Instance<PopManager>().ShowPop(PopView.systemMessage, nd => {
                nd.getComponent(SystemMessage).InitContent("材料不足")
            })
            return;
        }
        GameData.playerData.upgradeTime = Date.now();
        GameData.playerData.upgradeTotal = config.upgradeCountDown;
        config.upgradeSpend.forEach(element => {
            let num = element[1]
            GameData.GetNumByType(element[0], num * -1);
        });
        this.InitUpgrade();

    }

    OnClose() {
        SoundManager.Instance<SoundManager>().PlayEffect(GameData.btnClick);
        this.node.destroy();
    }

    OnBtnCutTime() {
        SoundManager.Instance<SoundManager>().PlayEffect(GameData.btnClick);
        if (this.isLock) return
        AppControll.Platform.ShowRewardVideoAd(this, (bool, str) => {
            if (bool) {
                GameData.playerData.upgradeTotal -= Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.videoCutTime).value);
            }
        })
    }

}


